package com.itstyle.quartz.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itstyle.quartz.entity.Result;
import com.itstyle.quartz.job.kettleJob;
import com.itstyle.quartz.kettleUtil.DateUtil;
import com.itstyle.quartz.kettleUtil.FileReadUtil;
import com.itstyle.quartz.kettleUtil.LogUtil;
import com.itstyle.quartz.service.dao.ACLineDotService;
import com.itstyle.quartz.service.dao.IJobService;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.util.*;

/**
 * @author ycj
 * @version 1.0
 * @description
 * @date 2021/1/7 15:50
 */
public class ReadFileThread implements Runnable {

    private JobKey jobkey;
    private String quartzid;
    private IJobService jobService;
    private ACLineDotService acLineDotService;
    private static final Logger logger = LoggerFactory.getLogger(kettleJob.class);


    List<File> filePathsList = new ArrayList<File>();
    int index = 0;

    public ReadFileThread(String path,ACLineDotService acLineDotService,JobKey jobkey,IJobService jobService,String quartzid) {
        this.acLineDotService = acLineDotService;
        //创建解析路径文件
        File f = new File(path);
        this.jobkey=jobkey;
        this.jobService=jobService;
        this.quartzid=quartzid;
        //获取路径下所有文件
        getFileList(f);
    }

    private void getFileList(File f) {
        File[] filePaths = f.listFiles();
        for (File s : filePaths) {
            if (s.isDirectory()) {
            } else {
                //线程公共容器，确保不重复读取一个文件
                filePathsList.add(s);
            }
        }
    }

    @Override
    public void run() {
        File file2 = null;
        //返回结果
        Result result = null;
        int error = 0;
        String filename = "";
        // 对参数进行处理，约定为ktr不传参数，所有传参数的都为Job任务去执行
        JSONObject params = null;
        //日志状态信息给定默认值
        String message="任务执行中！";
        //任务状态
        String status="正在执行";
        //使用集群时显示主机IP
        String hostIp = "";

//        String errorfilepath = "/home/dcloud/kettle_data_manage/kettle_manage/error";
//        String transferFilePath = "/home/dcloud/kettle_data_manage/kettle_manage/bak";
        String transferFilePath = "D:\\dianli\\k\\bak";
        String errorfilepath = "D:\\dianli\\k\\error";

        //同步锁，以公共容器为锁，防止出现同一文件多次读取
        while (index < filePathsList.size()) {
            synchronized (this.filePathsList) {
                if (index >= filePathsList.size()) {
                    continue;
                }
                file2 = filePathsList.get(index);
                index++;
            }

            String filepath = file2.getPath();

            //对路径进行分割，获取文件名
            String[] split1 = filepath.split("\\\\");
            //获取文件名
            filename = split1[split1.length - 1];

            //查询此文件是否已被读取过
            List<String> fileName = acLineDotService.findFileName(filename);
            if (fileName.size()>0) {
                logger.info("此文件已读取过:"+filepath);

                //已被读取，转移路径
                File file = new File(transferFilePath + "\\\\" + filename);
                //执行文件工具类转移文件方法
                FileReadUtil.transferFile(filepath,transferFilePath+"\\\\"+filename);
                continue;
            }

            String[] split = filepath.split("\\.");
            if (split[split.length-1].equals("eh") || split[split.length-1].equals("status") ) {
                logger.info("此文件为eh或status文件，不保存其数据:"+filepath);
                //执行文件工具类转移文件方法
                FileReadUtil.transferFile(filepath,errorfilepath+"\\\\"+filename);
                continue;
            }

            File file = new File(filepath);
            if (!file.exists()) {
                logger.info("文件不存在或者为空:"+filepath);
                if (!file.isDirectory()) {
                    //执行文件工具类转移文件方法
                    FileReadUtil.transferFile(filepath,errorfilepath+"\\\\"+filename);
                }
                continue;
            }

             //判断文件是否为文件夹
            if (!file.isDirectory()) {
                //读取文件
                result = save(filepath);
                if (!result.get("code").equals(0)) {
                    error=1;
                }
            }else {
                continue;
            }

            if (result.get("code").equals(0)) {
                //保存已读取文件信息记录
                acLineDotService.saveFileName(filename);
            }

            try {
                //线程等待
                Thread.sleep(300);
            } catch (InterruptedException e2) {
                e2.printStackTrace();
            }

            if (result!=null) {
                logger.info("JOB任务执行结束：jobkey=" + jobkey.toString() + "; result" + result.toString());

                if(result.get("code").equals(0) && error==0){
                    //处理日志信息
                    status="文件读取执行成功";
                    message="执行主机IP"+hostIp+"; 任务执行成功!";
                    LogUtil.updateJobKettleLogs(quartzid,jobkey,jobService,status,message);
                }else {
                    //处理日志信息
                    status="文件读取执行失败";
                    message="执行主机IP"+hostIp+"; 执行失败! 请检查执行Ketlle job是否有异常。";
                    LogUtil.updateJobKettleLogs(quartzid,jobkey,jobService,status,message);
                }
            }else {
                logger.info("JOB任务执行结束：jobkey=" + jobkey.toString() + ";");
                //处理日志信息
                status="文件读取执行成功";
                message="执行主机IP"+hostIp+"; 任务执行成功!";
                LogUtil.updateJobKettleLogs(quartzid,jobkey,jobService,status,message);
            }
        }
    }

    public Result save(String path) {
//        String transferFilePath = "/home/dcloud/kettle_data_manage/kettle_manage/bak";
//        String transferFileErrorPath = "/home/dcloud/kettle_data_manage/kettle_manage/error";
        String transferFilePath = "D:\\dianli\\k\\bak";
        String transferFileErrorPath = "D:\\dianli\\k\\error";

        //路径进行分割
        String[] split = path.split("\\.");
        //获取文件后缀
        String type = split[1];

        File file = new File(transferFilePath);
        File errorfile = new File(transferFileErrorPath);
        //判断文件是否存在
        if (!file.exists()) {
            file.mkdir();
        }
        if (!errorfile.exists()) {
            file.mkdir();
        }

        //路径分割
        String[] split3 = path.split("\\\\");
        String filename = split3[split3.length - 1];

        //获取城市名称
        String[] city = filename.split("_");
        String cityname = city[0];

        HashMap<String, List<String>> read = null;
        try {
            logger.info("读取该文件路径:" + path);
            //读取文件，返回一个数据集合
            read = FileReadUtil.read(path);

            logger.info("开始保存文件:" + path);
            logger.info("开始保存文件:" + cityname);

            //数据保存
            if(type.equals("DT") && filename.contains("xn")
                    || type.equals("DT") && filename.contains("hx")
                    || type.equals("DT") && filename.contains("hb")
                    || type.equals("DT") && filename.contains("gl")) {
                HashMap<String, List<String>> readDT = FileReadUtil.readDT(path);
                acLineDotService.Dtsave(readDT,type,cityname,filename);
            }else {
                acLineDotService.save(read, type,cityname,filename);
            }

            //文件转移
            FileReadUtil.transferFile(path,transferFilePath+"\\\\"+filename);
        } catch (Exception e) {
            logger.info("文件数据保存失败:" + path);
            //保存文件信息
            acLineDotService.saveErrorFileName(filename);
            //文件转移
            FileReadUtil.transferFile(path,transferFileErrorPath+"\\\\"+filename);
            return Result.error();
        }
        return Result.ok();
    }
}
